package jp.gotenyama.android.widget.fusen;

import jp.gotenyama.widget.fusen.R;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class MyFusenWidgetProvider extends AppWidgetProvider {
	
	private static final String ACTION_MY_CLICK = "jp.gotenyama.widget.fusen.ACTION_MY_CLICK";
	
	@Override
	public void onEnabled(Context context) {
		Log.v("MyFusenWidgetProvider", "onEnabled");
		super.onEnabled(context);
	}
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.v("MyFusenWidgetProvider", "onUpdate");
		super.onUpdate(context, appWidgetManager, appWidgetIds);
        Intent serviceIntent = new Intent(context, MyService.class);
        //定期的な何かの処理を行うためサービスを毎回起動する
        context.startService(serviceIntent);
	}
	
    public static class MyService extends Service {
        @Override
        public void onStart(Intent intent, int startId) {
            ComponentName thisWidget = new ComponentName(this, MyFusenWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            
            //RemoteViewsというクラスでウィジェットにアクセスできる
            RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.main);
            if (ACTION_MY_CLICK.equals(intent.getAction())) {
            	Intent i = new Intent();
            	i.setClass(this, MyFusenWidgetActivity.class);
            	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            	startActivity(i);
//                remoteViews.setTextViewText(R.id.fusenText, textBody);
            }
            
            Intent clickIntent = new Intent();
            clickIntent.setAction(ACTION_MY_CLICK);
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, clickIntent, 0);
            
            //付箋のレイアウト自体にクリックされたときに起動するインテントを設定
            remoteViews.setOnClickPendingIntent(R.id.mainLayout, pendingIntent);
            
            manager.updateAppWidget(thisWidget, remoteViews);
            stopSelf();
        }

		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
    }    
    
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		Log.v("MyFusenWidgetProvider", "onDeleted");
		super.onDeleted(context, appWidgetIds);
	}

	@Override
	public void onDisabled(Context context) {
		Log.v("MyFusenWidgetProvider", "onDisabled");
		super.onDisabled(context);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.v("MyFusenWidgetProvider", "onReceive");
		super.onReceive(context, intent);
	}
}
